package wng.su;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.Typeface;
import android.graphics.drawable.Icon;
import android.net.TrafficStats;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextPaint;

import java.text.SimpleDateFormat;
import java.util.Date;


public class S extends Service implements Runnable{
    public static final int NOTIFICATION_ID = -1010302975;
    Handler handler = new Handler();

    @Override
    public void run() {
        flashData();
        int timeBeforeNextSec = 1000 - (int)(System.currentTimeMillis() % 1000);
        handler.postDelayed(this,timeBeforeNextSec + 1);
    }

    NotificationManager notificationManager;
    Notification.Builder builder;
    Bitmap bitmap;
    Canvas canvas;
    TextPaint tpNumberSmall;
    TextPaint tpUnit;
    TextPaint tpNumberBig;
    long lastTotalRxBytes = 0;
    long lastTotalTxBytes = 0;

    SimpleDateFormat showSecondSDF = new SimpleDateFormat("HH:mm:ss");
    Date cachedDate = new Date();


    public static String formatUnit(long bytesize) {
        if (bytesize >= 1024000) {
            return String.format("%.1f", Double.valueOf(bytesize/1048576.0))+"MB";

        }
        else if (bytesize >= 1000) {
            return String.format("%.0f", Double.valueOf(bytesize/1024.0))+"KB";
        }else
            return String.format("% 3d", Long.valueOf(bytesize)) + "B";
    }


    public Notification notification(long downloadByte, long uploadByte) {
        if (builder == null) {
            if (Build.VERSION.SDK_INT > 26) {
                NotificationChannel notificationChannel = new NotificationChannel("wangsu", "网速状态栏", NotificationManager.IMPORTANCE_DEFAULT);
                notificationChannel.setLockscreenVisibility(-1);
                if (Build.VERSION.SDK_INT >= 29) {
                    notificationChannel.setAllowBubbles(false);
                }
                notificationChannel.enableLights(false);
                notificationChannel.enableVibration(false);
                notificationChannel.setSound(null, null);
                notificationManager.createNotificationChannel(notificationChannel);
                builder = new Notification.Builder(this, "wangsu");
            } else {
                builder.setPriority( Notification.PRIORITY_DEFAULT);
                builder.setVibrate(null);
                builder.setSound(null);
                builder.setLights(0, 0, 0);
            }
            builder.setOngoing(true);
        }
        if(newStyle) {
            createIconNew(downloadByte, uploadByte);
        }else{
            createIconOld(downloadByte,uploadByte);
        }
        if(showSecond){
            cachedDate.setTime(System.currentTimeMillis() + 500);
            builder.setContentText(showSecondSDF.format(cachedDate)+"\t\t ↑" + formatUnitOld(uploadByte) + "/s\t\t ↓" + formatUnitOld(downloadByte) + "/s");
        }
        else{

            builder.setContentText("↑ " + formatUnitOld(uploadByte) + "/s\t\t ↓ " + formatUnitOld(downloadByte) + "/s");
        }
        builder.setSmallIcon(Icon.createWithBitmap(bitmap));
        return builder.build();
    }
    public void flashData() {
        notificationManager.notify(NOTIFICATION_ID, notification(TrafficStats.getTotalRxBytes() - lastTotalRxBytes, TrafficStats.getTotalTxBytes() - lastTotalTxBytes));
        lastTotalRxBytes = TrafficStats.getTotalRxBytes();
        lastTotalTxBytes = TrafficStats.getTotalTxBytes();
    }

    public void createIconNew(long d, long u) {


        canvas.drawColor(0, PorterDuff.Mode.CLEAR);
        long total=0;
        if (showDownload){
            total+=d;
        }
        if(showUpload){
            total+=u;
        }
        String number="";
        String unit="";
        if (total >= 1024000) {
            number=String.format("%.1f", Double.valueOf(total/1048576.0));
            unit="MB/s";
        }
        else if (total >= 1000) {
            number=String.format("%.0f", Double.valueOf(total/1024.0));
            unit="KB/s";
        }
        else if (!autoHide){
            number=String.format("%.0f", Double.valueOf(total/1.0));
            unit="B/s";
        }
        if (number.length()<3)
            canvas.drawText(number, 31.0f, 38.0f, tpNumberBig);
        else
            canvas.drawText(number, 31.0f, 35.0f, tpNumberSmall);
        canvas.drawText(unit, 31.0f, 63.0f, tpUnit);
    }

    boolean newStyle = true;
    boolean showDownload = true;
    boolean showUpload = true;
    boolean autoHide = true;
    boolean showSecond = false;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public void onCreate() {
        super.onCreate();
        int flag = getSharedPreferences("0",0).getInt("f",-1);

        newStyle = (flag & 0x1) > 0;
        showDownload = (flag & 0x2) > 0;
        showUpload = (flag & 0x4) > 0;
        autoHide = (flag & 0x8) > 0;
        showSecond = (flag & 0x10) > 0;

        notificationManager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
        bitmap = Bitmap.createBitmap(64, 64, Bitmap.Config.ARGB_8888);
        canvas = new Canvas(bitmap);
        tpNumberSmall = new TextPaint();
        tpNumberSmall.setAntiAlias(true);
        tpNumberSmall.setTextSize(40.0f);
        tpNumberSmall.setColor(-1);
        tpNumberSmall.setTypeface(Typeface.DEFAULT_BOLD);
        tpNumberSmall.setTextAlign(Paint.Align.CENTER);
        tpNumberSmall.setStyle(Paint.Style.FILL);
        tpNumberSmall.setFakeBoldText(true);
        tpUnit = new TextPaint();
        tpUnit.setAntiAlias(true);
        tpUnit.setTextSize(27.0f);
        tpUnit.setColor(-1);
        tpUnit.setTypeface(Typeface.MONOSPACE);
        tpUnit.setTextAlign(Paint.Align.CENTER);
        tpUnit.setStyle(Paint.Style.FILL);
        tpUnit.setFakeBoldText(true);
        tpNumberBig = new TextPaint();
        tpNumberBig.setAntiAlias(true);
        tpNumberBig.setTextSize(50.0f);
        tpNumberBig.setColor(-1);
        tpNumberBig.setTypeface(Typeface.DEFAULT_BOLD);
        tpNumberBig.setTextAlign(Paint.Align.CENTER);
        tpNumberBig.setStyle(Paint.Style.FILL);
        tpNumberBig.setFakeBoldText(true);
        this.oldFont = new TextPaint();
        this.oldFont.setAntiAlias(true);
        this.oldFont.setTextSize(this.oldSize);
        this.oldFont.setColor(-1);
        this.oldFont.setTypeface(Typeface.MONOSPACE);
        this.oldFont.setTextAlign(Paint.Align.CENTER);
        this.oldFont.setStyle(Paint.Style.FILL);
        this.oldFont.setFakeBoldText(true);
    }

    public int onStartCommand(Intent intent, int i2, int i3) {
        handler.removeCallbacks(this);
        handler.postDelayed(this, 1000);
        lastTotalRxBytes = TrafficStats.getTotalRxBytes();
        lastTotalTxBytes = TrafficStats.getTotalTxBytes();
        startForeground(NOTIFICATION_ID, notification(0, 0));
        return Service.START_STICKY;
    }

    @Override
    public void onDestroy() {
        handler.removeCallbacks(this);
        super.onDestroy();
    }

    // Legacy Type
    static long[] unitChangeThreshold = new long[]{1024000L, 1048576000L, Long.MAX_VALUE};
    static double[] unitDivide = new double[]{1024.0D, 1048576.0D, 1.073741824E9D};
    static String[] unitSuffixStr = new String[]{"K", "M", "G"};
    @SuppressLint("DefaultLocale")
    public static String formatUnitOld(long nByte) {
        if (nByte < 1000L) {
            if (nByte < 100L) {
                return String.format("% 3d", nByte)+"B";
            } else {
                return nByte + "B";
            }
        } else {
            for(int i = 0; i < 3; i++) {
                if (nByte < unitChangeThreshold[i]) {
                    double divided = (double)nByte / unitDivide[i];
                    String result;
                    if (divided < 9.9D) {
                        result = String.format("%.1f", divided);
                    } else if (divided < 100.0D) {
                        result = String.format(" %.0f", divided);
                    } else {
                        result = String.format("%.0f", divided);
                    }

                    return result + unitSuffixStr[i];
                }
            }

            return "wtfk";
        }
    }
    TextPaint oldFont;
    float oldSize = 25.0F;
    void createIconOld(long downloadByte, long uploadByte) {
        this.canvas.drawColor(0, PorterDuff.Mode.CLEAR);
        String var5 = formatUnitOld(uploadByte);
        this.canvas.drawText(var5, 31.0F, 31.0F, this.oldFont);
        String var6 = formatUnitOld(downloadByte);
        this.canvas.drawText(var6, 31.0F, 32.0F + this.oldSize, this.oldFont);
    }

}